import ol from "../utils/openlayers/ol.js";
function mapLayer() {
  //DXF文件解析后的点加载地图
  this.initMap = function () {
    let dxfMapInfo = new Object();
    const extent = [-20026376.39, -20048966.1, 20026376.39, 20048966.1]; //图片图层四至

    let projection = new ol.proj.Projection({
      //定义坐标系
      code: "EPSG:3857",
      units: "degree",
      extent: extent,
    });
    let view = new ol.View({
      center: [0, 0],
      zoom: 18, //地图比例
      maxZoom: 26,
      minZoom: 8,
      projection: projection,
    });

    let map = new ol.Map({
      target: "map",
      view: view,
      controls: ol.control
        .defaults()
        .extend([new ol.control.ZoomSlider({}), new ol.control.FullScreen()]),
    });
    dxfMapInfo.map = map;
    dxfMapInfo.view = view;
    dxfMapInfo.msg = "地图初始化完成";
    return dxfMapInfo;
  };

  this.Adaptive = function (lineDate, dxfMapInfo, oldT3Flag) {
    for (let i = 0; i < dxfMapInfo.map.getLayers().getLength(); ++i) {
      if (dxfMapInfo.map.getLayers().item(i).get("className") == "Adaptive") {
        dxfMapInfo.map.removeLayer(dxfMapInfo.map.getLayers().item(i));
      }
    }
    let coor_bigger_box;
    if (oldT3Flag) {
      //老T3 一条直线自适应地图 设置图在地图上展示的位置
      var p1 = [lineDate.orbitStartPosition, 0];
      var p2 = [lineDate.orbitEndPosition, 0];
      var p3 = [lineDate.orbitStartPosition, 0];
      var p4 = [lineDate.orbitEndPosition, 0];
      coor_bigger_box = [p1, p2, p4, p3];
    } else {
      const p1 = [mapLayer.getXmin(lineDate), mapLayer.getYmin(lineDate)];
      const p2 = [mapLayer.getXmax(lineDate), mapLayer.getYmin(lineDate)];
      const p3 = [mapLayer.getXmin(lineDate), mapLayer.getYmax(lineDate)];
      const p4 = [mapLayer.getXmax(lineDate), mapLayer.getYmax(lineDate)];
      coor_bigger_box = [p1, p2, p4, p3];
    }
    //自适应地图比例
    let shape_tmp = new ol.Feature({
      geometry: new ol.geom.Polygon([coor_bigger_box]),
    });
    // console.log('Adaptive', coor_bigger_box);
    let tmpLayer = new ol.layer.Vector({
      className: "Adaptive",
      source: new ol.source.Vector(),
      style: new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: "rgba(0,0,0,0)",
          width: 2,
        }),
        fill: new ol.style.Fill({
          color: "rgba(0,0,0,0)",
        }),
      }),
    });
    tmpLayer.getSource().addFeature(shape_tmp);
    let feature = tmpLayer.getSource().getFeatures()[0];
    let autoPolygon = feature.getGeometry();
    dxfMapInfo.view.fit(autoPolygon, dxfMapInfo.map.getSize(), {
      padding: [0, 0, 0, 0],
      constrainResolution: false,
    });
    dxfMapInfo.autoPolygon = autoPolygon;
    return autoPolygon;
  };

  this.dxflayerControl = function (ElementID, map) {
    const controls = document.getElementById(ElementID);
    controls.innerHTML = "";
    controls.innerHTML =
      "<input type=checkbox id=osm checked />地图路径<br/>" +
      "<input type=checkbox id=stamen checked />机器<br/>" +
      "<input type=checkbox id=bingmap checked/>RFID<br/>" +
      "<input type=checkbox id=viewpoint />巡检点<br/>";
    controls.addEventListener("click", (event) => {
      if (event.target.checked) {
        // 如果选中某一复选框
        // 通过DOM元素的id值来判断应该对哪个图层进行显示
        switch (event.target.id) {
          case "osm":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "Dxfline") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "bingmap":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "dxfRfid") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "stamen":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "robotPos") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "viewpoint":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "dxfViewpoint") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          default:
            break;
        }
      } else {
        // 如果取消某一复选框
        // 通过DOM元素的id值来判断应该对哪个图层进行隐藏
        switch (event.target.id) {
          case "osm":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "Dxfline") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "bingmap":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "dxfRfid") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "stamen":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "robotPos") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "viewpoint":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "dxfViewpoint") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          default:
            break;
        }
      }
    });
  };
  var clickTwoPoint = {};
  clickTwoPoint.time = 0;

  function myCallback(evt) {
    console.log("myCallback", evt);
    let PointX = evt.coordinate[0].toFixed(2);
    let PointY = evt.coordinate[1].toFixed(2);
    if (clickTwoPoint.time >= 1) {
      vm.wheelPoint.Y = clickTwoPoint.lastPoint[1];
      vm.wheelPoint.X = clickTwoPoint.lastPoint[0];
      let Y = PointY - clickTwoPoint.lastPoint[1];
      let X = PointX - clickTwoPoint.lastPoint[0];
      //坐标计算角度
      vm.wheelPoint.angle = getAngle(X, Y).toFixed(2);
      if (vm.wheelPoint.angle == null) {
        layer.msg("两点重复", { icon: 5, time: 1000 });
        clickTwoPoint = {};
        clickTwoPoint.time = 0;
        return;
      }
      layerAnglelShow();
      //坐标和角度值
      clickTwoPoint = {};
      clickTwoPoint.time = 0;
    } else {
      clickTwoPoint.lastPoint = [PointX, PointY];
      clickTwoPoint.time++;
    }
  }

  function layerAnglelShow() {
    let index = layer.open({
      type: 1,
      offset: "160px",
      skin: "layui-layer-molv",
      title: "坐标信息",
      area: ["300px", "230px"],
      shade: 0.3,
      shadeClose: false,
      content: jQuery("#wheelAngleShow"),
      btn: ["发送", "取消"],
      btn1: function (index) {
        layer.close(index);
        index = layer.open({
          title: "正在执行...",
          type: 1,
          closeBtn: 0,
          move: false,
          icon: 4,
          time: 10000,
        });
        $.ajax({
          type: "post",
          url:
            _baseApiUrl + "/sys/robot/wheelredirect?_" + new Date().getTime(),
          dataType: "json",
          data: {
            robotId: machineId,
            X: vm.wheelPoint.X,
            Y: vm.wheelPoint.Y,
            angle: vm.wheelPoint.angle,
          },
          success: function (r) {
            let result = JSON.parse(r.msg);
            layer.close(index);
            if (result.nErrcode == 0) {
              layer.msg("置信度: " + result.sFeedback, {
                icon: 1,
                time: 2000,
                closeBtn: 0,
                move: false,
                shade: 0.3,
              });
            } else {
              layer.msg("操作失败", {
                icon: 5,
                time: 1000,
                closeBtn: 0,
                move: false,
                shade: 0.3,
              });
            }
          },
        });
      },
      btn2: function (index) {
        //取消按钮
        layer.close(index);
      },
    });
  }

  function getAngle(x, y) {
    //求得角度
    let result = Math.atan2(Math.abs(y), Math.abs(x)) / (Math.PI / 180);
    //两点为点在同一个点上
    if (x == 0 && y == 0) {
      return null;
    }
    //第一象限直接返回角度
    if (x >= 0 && y >= 0) {
      return result;
    }
    //第二象限180-result
    if (x <= 0 && y >= 0) {
      return 180 - result;
    }
    //第三象限180+result
    if (x <= 0 && y <= 0) {
      return 180 + result;
    }
    //第四象限360-result
    if (x >= 0 && y <= 0) {
      return 360 - result;
    }
  }

  this.addClickEvent = function (map) {
    vm.wheelRedirectFlag = true;
    let key = map.on("click", myCallback);
    return key;
  };

  this.removeClickEvent = function (map) {
    vm.wheelRedirectFlag = false;
    map.un("click", myCallback);
    clickTwoPoint = {};
    clickTwoPoint.time = 0;
    // mapParam.map.ol.Observable.unByKey(mapParam.clickEventKey)
  };

  this.dxfMapline = function (data, className, map) {
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let coordinatesPolygon = data;
    let source = new ol.source.Vector();
    //矢量图层
    let vector_line = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "#2b8339",
          width: 4,
        }),
        image: new ol.style.Circle({
          radius: 2,
          fill: new ol.style.Fill({
            color: "#ffcc33",
          }),
        }),
      }),
    });
    let plygon = new ol.geom.LineString(coordinatesPolygon);
    //多边形要素类
    let feature = new ol.Feature({
      geometry: plygon,
    });
    // feature;
    vector_line.setZIndex(0);
    source.addFeature(feature);
    map.addLayer(vector_line);
  };

  this.dxfrobotPoint = function (point, className, map) {
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let pointSourceLayer = new ol.source.Vector();
    let coordinate = point;
    let pointMoveFeture = new ol.Feature({
      geometry: new ol.geom.Point(coordinate),
    });
    //矢量图层
    let vector_point = new ol.layer.Vector({
      className: className,
      source: pointSourceLayer,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 8,
        }),
        image: new ol.style.Icon({
          src: "../openlayers/img/icon-robot2.png",
          // src: baseURL + '/statics/static/client/icon-robot2.png',
          rotateWithView: false,
          // scale:0.8,
          // rotation: Math.atan2(3,3),
        }),
      }),
    });
    pointSourceLayer.addFeature(pointMoveFeture);
    vector_point.setZIndex(2);
    map.addLayer(vector_point);
    return pointMoveFeture;
  };

  this.DxfRfitPoint = function (data, className, map, clickFunc) {
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let coordinatesPolygon1 = new Array(data.length);
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        coordinatesPolygon1[i] = [
          data[i].position[0],
          data[i].position[1],
          data[i].movePosition,
        ];
      }
    }
    let features = new Array(coordinatesPolygon1.length);
    for (let i = 0; i < coordinatesPolygon1.length; ++i) {
      let coordinate = [coordinatesPolygon1[i][0], coordinatesPolygon1[i][1]];
      features[i] = new ol.Feature(new ol.geom.Point(coordinate));
      features[i].set("movePosition", coordinatesPolygon1[i][2]);
    }
    let source = new ol.source.Vector();
    let vector_point = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 8,
        }),
        image: new ol.style.Icon({
          src: "../openlayers/img/icon-default3.png",
          rotateWithView: false,
        }),
      }),
    });
    vector_point.setZIndex(1);
    source.addFeatures(features);
    map.addLayer(vector_point);
    if (typeof clickFunc === "function") {
      //如果有点击函数则添加点击事件
      map.on("singleclick", function (e) {
        //e.pixel [104, 225];
        displayFeatureInfo(e.pixel);
      });

      let displayFeatureInfo = function (pixel) {
        if (typeof clickFunc === "function") {
          let features = [];
          map.forEachFeatureAtPixel(pixel, function (feature) {
            features.push(feature);
          });
          if (features.length > 0) {
            let i, ii;
            for (i = 0, ii = features.length; i < ii; ++i) {
              let movePosition = features[i].get("movePosition");
              if (movePosition != undefined) {
                layer.confirm("确定机器移动到此位置？", function () {
                  clickFunc(movePosition);
                  // setPosition(6,movePosition);
                  layer.close(layer.index);
                });
              }
            }
          }
        }
      };
    }
  };
  this.DxfViewPoint = function (data, className, map, clickFunc) {
    console.log(data);
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let coordinatesPolygon1 = new Array(data.length);
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        coordinatesPolygon1[i] = [
          data[i].position[0],
          data[i].position[1],
          data[i].movePosition,
        ];
      }
    }
    let features = new Array(coordinatesPolygon1.length);
    for (let i = 0; i < coordinatesPolygon1.length; ++i) {
      let coordinate = [coordinatesPolygon1[i][0], coordinatesPolygon1[i][1]];
      features[i] = new ol.Feature(new ol.geom.Point(coordinate));
      features[i].set("movePosition", coordinatesPolygon1[i][2]);
    }

    let source = new ol.source.Vector();
    let vector_point = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 8,
        }),
        image: new ol.style.Icon({
          src: "../openlayers/img/icon-default.png",
          rotateWithView: false,
        }),
      }),
    });
    vector_point.setVisible(false);
    vector_point.setZIndex(1);
    source.addFeatures(features);
    map.addLayer(vector_point);
    if (typeof clickFunc === "function") {
      //如果有点击函数则添加点击事件
      map.on("singleclick", function (evt) {
        console.warn("evt.pixel", evt.pixel);
        displayFeatureInfo(evt.pixel);
      });
      let displayFeatureInfo = function (pixel) {
        if (typeof clickFunc === "function") {
          let features = [];
          map.forEachFeatureAtPixel(pixel, function (feature) {
            features.push(feature);
          });
          console.warn("features数据", features);
          if (features.length > 0) {
            let i;
            for (i = 0; i < features.length; ++i) {
              let movePosition = features[i].get("movePosition");
              console.warn("定义参数", movePosition);
              if (movePosition != undefined) {
                layer.confirm("确定机器移动到此位置？", function () {
                  clickFunc(movePosition);
                  layer.close(layer.index);
                });
              }
            }
          }
        }
      };
    }
  };

  this.getCenter = function (mapAllParam) {
    mapAllParam.view.fit(mapAllParam.autoPolygon, mapAllParam.map.getSize(), {
      padding: [0, 0, 0, 0],
      constrainResolution: false,
    });
  };

  this.robotMovePoint = function (point, mapAllParam) {
    if (mapAllParam.pointMoveFeture != undefined) {
      mapAllParam.pointMoveFeture.setGeometry(new ol.geom.Point(point));
      // console.log(mapAllParam.pointMoveFeture);
      /*for (let i = 0; i < mapAllParam.map.getLayers().getLength(); ++i) { .getStyle().getImage().getRotation()
                if (mapAllParam.map.getLayers().item(i).get("className") == "robotPos") {
                    console.log(mapAllParam.map.getLayers().item(i).getImage().getRotation())
                }
            }*/
    }
  };

  this.smapAdaptive = function (mapDetailList, smapInfo) {
    for (let i = 0; i < smapInfo.map.getLayers().getLength(); ++i) {
      if (smapInfo.map.getLayers().item(i).get("className") == "Adaptive") {
        smapInfo.map.removeLayer(smapInfo.map.getLayers().item(i));
      }
    }
    let minPos = {};
    let maxPos = {};
    for (let i = 0; i < mapDetailList.length; i++) {
      if (mapDetailList[i].minPos != undefined) {
        minPos.dotX = mapDetailList[i].minPos.dotX;
        minPos.dotY = mapDetailList[i].minPos.dotY;
      }
      if (mapDetailList[i].maxPos != undefined) {
        maxPos.dotX = mapDetailList[i].maxPos.dotX;
        maxPos.dotY = mapDetailList[i].maxPos.dotY;
      }
    }
    const p1 = [minPos.dotX, minPos.dotY];
    const p2 = [maxPos.dotX, minPos.dotY];
    const p3 = [maxPos.dotX, maxPos.dotY];
    const p4 = [minPos.dotX, maxPos.dotY];
    const coor_bigger_box = [p1, p2, p3, p4];
    let shape_tmp = new ol.Feature({
      geometry: new ol.geom.Polygon([coor_bigger_box]),
    });
    let tmpLayer = new ol.layer.Vector({
      className: "Adaptive",
      source: new ol.source.Vector(),
      style: new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: "rgba(0,0,0,0)",
          width: 2,
        }),
        fill: new ol.style.Fill({
          color: "rgba(0,0,0,0)",
        }),
      }),
    });
    tmpLayer.getSource().addFeature(shape_tmp);
    let feature = tmpLayer.getSource().getFeatures()[0];
    let autoPolygon = feature.getGeometry();
    smapInfo.view.fit(autoPolygon, smapInfo.map.getSize(), {
      padding: [0, 0, 0, 0],
      constrainResolution: false,
    });
    smapInfo.autoPolygon = autoPolygon;
    return autoPolygon;
  };

  this.smaplayerControl = function (ElementID, map) {
    const controls = document.getElementById(ElementID);
    controls.innerHTML = "";
    controls.innerHTML =
      "<input type=checkbox id=osm />地图路径<br/>" +
      " <input type=checkbox id=bingmap checked/>站点<br/>" +
      "<input type=checkbox id=charge checked />充电桩<br/>" +
      "<input type=checkbox id=stamen checked />机器<br/>" +
      "<input type=checkbox id=mapClick unchecked />手动定位<br/>";
    controls.addEventListener("click", (event) => {
      if (event.target.checked) {
        // 如果选中某一复选框
        // 通过DOM元素的id值来判断应该对哪个图层进行显示
        switch (event.target.id) {
          case "osm":
            //初始化路径
            this.smapNormalPoint(vm.Pointlist, "Dxfline", vm.mapParam.map);
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "Dxfline") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "bingmap":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "dxfRfid") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "stamen":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "robotPos") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "charge":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "charge") {
                map.getLayers().item(i).setVisible(true);
              }
            }
            break;
          case "mapClick":
            this.addClickEvent(map);
            break;
          default:
            break;
        }
      } else {
        // 如果取消某一复选框
        // 通过DOM元素的id值来判断应该对哪个图层进行隐藏
        switch (event.target.id) {
          case "osm":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "Dxfline") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "bingmap":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "dxfRfid") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "stamen":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "robotPos") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "charge":
            for (let i = 0; i < map.getLayers().getLength(); ++i) {
              if (map.getLayers().item(i).get("className") == "charge") {
                map.getLayers().item(i).setVisible(false);
              }
            }
            break;
          case "mapClick":
            this.removeClickEvent(map);
            break;

          default:
            break;
        }
      }
    });
  };
  //MultiLineString
  this.smapMultiLine = function (mapDetailList, className, map) {
    let advanceLineList;
    for (let i = 0; i < mapDetailList.length; i++) {
      if (mapDetailList[i].advancedLineList != undefined) {
        advanceLineList = new Array(mapDetailList[i].advancedLineList.length);
        for (let j = 0; j < mapDetailList[i].advancedLineList.length; j++) {
          const line = new Array(2);
          line[0] = [
            mapDetailList[i].advancedLineList[j].startPos.dotX,
            mapDetailList[i].advancedLineList[j].startPos.dotY,
          ];
          line[1] = [
            mapDetailList[i].advancedLineList[j].endPos.dotX,
            mapDetailList[i].advancedLineList[j].endPos.dotY,
          ];
          advanceLineList[j] = line;
          console.log("advancedLineList");
        }
      }
    }
    console.log(advanceLineList);
    if (advanceLineList != undefined) {
      let feature = new ol.Feature(
        new ol.geom.MultiLineString(advanceLineList)
      );
      let source = new ol.source.Vector();
      //矢量图层
      let vector_line = new ol.layer.Vector({
        className: className,
        source: source,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: "rgba(255, 255, 255, 0.1)",
          }),
          stroke: new ol.style.Stroke({
            color: "red",
            width: 1,
          }),
          image: new ol.style.Circle({
            radius: 2,
            fill: new ol.style.Fill({
              color: "#ff3344",
            }),
          }),
        }),
      });
      vector_line.setZIndex(0);
      source.addFeature(feature);
      map.addLayer(vector_line);
    }
  };
  //MultiPoint
  this.smapNormalPoint = function (mapDetailList, className, map) {
    if (this.initSmapNormalPoint) {
      return;
    }
    console.log("this.smapNormalPoint");
    this.initSmapNormalPoint = true;
    //查询普通点
    $.ajax({
      type: "post",
      url: _baseApiUrl + "report/map/smapList.normalPosList",
      dataType: "json",
      data: {
        robotId: machineId,
      },
      success: function (r) {
        var coordinate = r.normalPosList;
        var pointMoveFeture = new ol.Feature({
          geometry: new ol.geom.MultiPoint(coordinate),
        });
        let source = new ol.source.Vector();
        var vector_point = new ol.layer.Vector({
          className: className,
          source: source,
          style: new ol.style.Style({
            fill: new ol.style.Fill({
              color: "rgba(255, 255, 255, 0.1)",
            }),
            stroke: new ol.style.Stroke({
              color: "red",
              width: 8,
            }),
            image: new ol.style.Circle({
              radius: 0.5,
              fill: new ol.style.Fill({
                color: "rgba(241,186,19,0.99)",
              }),
            }),
          }),
        });
        source.addFeature(pointMoveFeture);
        vector_point.setZIndex(1);
        map.addLayer(vector_point);
      },
    });
  };

  this.smapStationPoint = function (
    mapDetailList,
    className,
    map,
    clickFunc,
    rightClickFunc
  ) {
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let coordinatesPolygon1;
    for (let i = 0; i < mapDetailList.length; i++) {
      if (mapDetailList[i].advancedPointList != undefined) {
        coordinatesPolygon1 = new Array(
          mapDetailList[i].advancedPointList.length
        );
        for (let j = 0; j < mapDetailList[i].advancedPointList.length; j++) {
          if (
            mapDetailList[i].advancedPointList[j].className == "LocationMark"
          ) {
            coordinatesPolygon1[j] = [
              mapDetailList[i].advancedPointList[j].dotX,
              mapDetailList[i].advancedPointList[j].dotY,
              mapDetailList[i].advancedPointList[j].instanceName,
              mapDetailList[i].advancedPointList[j].dir,
            ];
          }
        }
      }
    }
    let features = new Array(coordinatesPolygon1.length);
    for (let i = 0; i < coordinatesPolygon1.length; ++i) {
      let coordinate = [coordinatesPolygon1[i][0], coordinatesPolygon1[i][1]];
      features[i] = new ol.Feature(new ol.geom.Point(coordinate));
      features[i].set("instanceName", coordinatesPolygon1[i][2]);
      features[i].set(
        "dotXYZ",
        coordinatesPolygon1[i][0] +
          "," +
          coordinatesPolygon1[i][1] +
          "," +
          coordinatesPolygon1[i][3]
      );
    }
    let source = new ol.source.Vector();
    let vector_point = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 8,
        }),
        image: new ol.style.Circle({
          radius: 3,
          fill: new ol.style.Fill({
            color: "rgba(245,13,216,0.99)",
          }),
        }),
      }),
    });
    vector_point.setZIndex(1);
    source.addFeatures(features);
    map.addLayer(vector_point);
    if (typeof clickFunc === "function") {
      map.on("singleclick", function (evt) {
        displayFeatureInfo(evt.pixel);
      });
      let displayFeatureInfo = function (pixel) {
        let features = [];
        map.forEachFeatureAtPixel(pixel, function (feature) {
          features.push(feature);
        });
        if (features.length > 0) {
          let i, ii;
          for (i = 0, ii = features.length; i < ii; ++i) {
            let instanceName = features[i].get("instanceName");
            if (features[i].get("instanceName") != undefined) {
              layer.confirm("确定机器移动到此位置？", function () {
                clickFunc(instanceName);
                // movePositon(rosClientControl,instanceName);
                layer.close(layer.index);
              });
            }
          }
        }
      };
    }
    if ($("#wheelAddViewPoint").length > 0) {
      if (typeof rightClickFunc === "function") {
        map.on("contextmenu", function (evt) {
          //contextmenu
          evt.preventDefault();
          $("#CustomPreset").hide();
          addPointInfo(evt.pixel);
        });
        let addPointInfo = function (pixel) {
          if (typeof clickFunc === "function") {
            let features = [];
            map.forEachFeatureAtPixel(pixel, function (feature) {
              features.push(feature);
            });
            if (features.length > 0) {
              let i, ii;
              for (i = 0, ii = features.length; i < ii; ++i) {
                let instanceName = features[i].get("instanceName");
                let dotXYZ = features[i].get("dotXYZ");
                $("#wheelStationPointName").val(instanceName);
                $("#wheelCurPos").val(dotXYZ);
                $("#armPosition").val(vm.T7Pos.fArmPos);
                if (instanceName != undefined) {
                  layer.open({
                    type: 1,
                    offset: "160px",
                    skin: "layui-layer-molv",
                    title: "加入巡检点",
                    area: ["500px", "340px"],
                    shade: 0.3,
                    shadeClose: false,
                    content: jQuery("#wheelAddViewPoint"),
                    btn: ["确定", "取消"],
                    btn1: function (index) {
                      let armPosition = $("#wheelArmpos").val();
                      let viewPointName = $("#wheelViewPointName").val();
                      if (
                        viewPointName == undefined ||
                        viewPointName == null ||
                        viewPointName == ""
                      ) {
                        $("#wheelViewPointMsg").text("请填写巡检点名称");
                        return;
                      }
                      if (
                        armPosition == undefined ||
                        armPosition == null ||
                        armPosition === ""
                      ) {
                        $("#wheelViewPointMsg").text("无法获取升降臂位置");
                        return;
                      }
                      rightClickFunc(instanceName, dotXYZ, index);
                    },
                    btn2: function (index) {
                      //取消按钮
                      layer.close(index);
                    },
                  });
                }
              }
            }
          }
        };
      }
    }
  };

  this.smapStationPointOnlyLeft = function (mapDetailList, className, map) {
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let coordinatesPolygon1;
    for (let i = 0; i < mapDetailList.length; i++) {
      if (mapDetailList[i].advancedPointList != undefined) {
        coordinatesPolygon1 = new Array(
          mapDetailList[i].advancedPointList.length
        );
        for (let j = 0; j < mapDetailList[i].advancedPointList.length; j++) {
          if (
            mapDetailList[i].advancedPointList[j].className == "LocationMark"
          ) {
            coordinatesPolygon1[j] = [
              mapDetailList[i].advancedPointList[j].dotX,
              mapDetailList[i].advancedPointList[j].dotY,
              mapDetailList[i].advancedPointList[j].instanceName,
              mapDetailList[i].advancedPointList[j].dir,
            ];
          }
        }
      }
    }
    let features = new Array(coordinatesPolygon1.length);
    for (let i = 0; i < coordinatesPolygon1.length; ++i) {
      let coordinate = [coordinatesPolygon1[i][0], coordinatesPolygon1[i][1]];
      features[i] = new ol.Feature(new ol.geom.Point(coordinate));
      features[i].set("instanceName", coordinatesPolygon1[i][2]);
      features[i].set(
        "dotXYZ",
        coordinatesPolygon1[i][0] +
          "," +
          coordinatesPolygon1[i][1] +
          "," +
          coordinatesPolygon1[i][3]
      );
    }
    let source = new ol.source.Vector();
    let vector_point;
    if (className == "charge") {
      vector_point = new ol.layer.Vector({
        className: className,
        source: source,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: "rgba(255, 255, 255, 0.1)",
          }),
          stroke: new ol.style.Stroke({
            color: "red",
            width: 8,
          }),
          image: new ol.style.Circle({
            radius: 4,
            fill: new ol.style.Fill({
              color: "rgba(0,0,255,0.99)",
            }),
          }),
        }),
      });
    }
    if ((className = "dxfRfid")) {
      vector_point = new ol.layer.Vector({
        className: className,
        source: source,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: "rgba(255, 255, 255, 0.1)",
          }),
          stroke: new ol.style.Stroke({
            color: "red",
            width: 8,
          }),
          image: new ol.style.Circle({
            radius: 4,
            fill: new ol.style.Fill({
              color: "rgba(245,13,216,0.99)",
            }),
          }),
        }),
      });
    }
    vector_point.setZIndex(1);
    source.addFeatures(features);
    map.addLayer(vector_point);
  };
  this.smapClick = function (map, clickFunc) {
    if (typeof clickFunc === "function") {
      map.on("singleclick", function (evt) {
        displayFeatureInfo(evt.pixel);
      });
      let displayFeatureInfo = function (pixel) {
        if (!vm.wheelRedirectFlag) {
          let features = [];
          map.forEachFeatureAtPixel(pixel, function (feature) {
            features.push(feature);
          });
          if (features.length > 0) {
            let i, ii;
            for (i = 0, ii = features.length; i < ii; ++i) {
              let instanceName = features[i].get("instanceName");
              if (features[i].get("instanceName") != undefined) {
                if (!vm.wheelRedirectFlag) {
                  layer.confirm("确定机器移动到此位置？", function () {
                    clickFunc(instanceName);
                    // movePositon(rosClientControl,instanceName);
                    layer.close(layer.index);
                  });
                }
              }
            }
          }
        }
      };
    }
  };

  this.smapChargePoint = function (mapDetailList, className, map, clickFunc) {
    console.log(mapDetailList);
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let coordinatesPolygon1;
    for (let i = 0; i < mapDetailList.length; i++) {
      if (mapDetailList[i].chargeArr != undefined) {
        console.log(mapDetailList[i].chargeArr.length);
        coordinatesPolygon1 = new Array(mapDetailList[i].chargeArr.length);
        for (let j = 0; j < mapDetailList[i].chargeArr.length; j++) {
          coordinatesPolygon1[j] = [
            mapDetailList[i].chargeArr[j].dotX,
            mapDetailList[i].chargeArr[j].dotY,
            mapDetailList[i].chargeArr[j].instanceName,
            mapDetailList[i].chargeArr[j].dir,
          ];
        }
      }
    }
    let features = new Array(coordinatesPolygon1.length);
    for (let i = 0; i < coordinatesPolygon1.length; ++i) {
      let coordinate = [coordinatesPolygon1[i][0], coordinatesPolygon1[i][1]];
      features[i] = new ol.Feature(new ol.geom.Point(coordinate));
      features[i].set("instanceName", coordinatesPolygon1[i][2]);
      features[i].set(
        "dotXYZ",
        coordinatesPolygon1[i][0] +
          "," +
          coordinatesPolygon1[i][1] +
          "," +
          coordinatesPolygon1[i][3]
      );
    }
    let source = new ol.source.Vector();
    let vector_point = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 8,
        }),
        image: new ol.style.Circle({
          radius: 4,
          fill: new ol.style.Fill({
            color: "rgba(0,0,255,0.99)",
          }),
        }),
      }),
    });
    vector_point.setZIndex(1);
    source.addFeatures(features);
    map.addLayer(vector_point);
    if (typeof clickFunc === "function") {
      map.on("singleclick", function (evt) {
        displayFeatureInfo(evt.pixel);
      });
      let displayFeatureInfo = function (pixel) {
        let features = [];
        map.forEachFeatureAtPixel(pixel, function (feature) {
          features.push(feature);
        });
        if (features.length > 0) {
          let i, ii;
          for (i = 0, ii = features.length; i < ii; ++i) {
            let instanceName = features[i].get("instanceName");
            if (features[i].get("instanceName") != undefined) {
              layer.confirm("确定机器移动到此位置？", function () {
                clickFunc(instanceName);
                // movePositon(rosClientControl,instanceName);
                layer.close(layer.index);
              });
            }
          }
        }
      };
    }
  };

  this.smaprobotPoint = function (point, className, map) {
    for (let i = 0; i < map.getLayers().getLength(); ++i) {
      if (map.getLayers().item(i).get("className") == className) {
        map.removeLayer(map.getLayers().item(i));
      }
    }
    let pointSourceLayer = new ol.source.Vector();
    let coordinate = point;
    let pointMoveFeture = new ol.Feature({
      geometry: new ol.geom.Point(coordinate),
    });
    //矢量图层
    let vector_point = new ol.layer.Vector({
      className: className,
      source: pointSourceLayer,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 8,
        }),
        image: new ol.style.Icon({
          src: "../openlayers/img/icon-robot2.png",
          rotateWithView: false,
        }),
      }),
    });
    pointSourceLayer.addFeature(pointMoveFeture);
    vector_point.setZIndex(2);
    map.addLayer(vector_point);
    return pointMoveFeture;
  };

  this.smapOneLine = function (data, className) {
    //只画一根线
    var coordinatesPolygon = data;
    //瓦片图层
    var tileLayer = new ol.layer.Tile({
      source: new ol.source.OSM(),
    });
    var source = new ol.source.Vector();
    //矢量图层
    var vector_line = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "#2b8339",
          width: 4,
        }),
        image: new ol.style.Circle({
          radius: 2,
          fill: new ol.style.Fill({
            color: "#ffcc33",
          }),
        }),
      }),
    });
    //多边形此处注意一定要是[坐标数组]
    // console.log("画线的坐标集合为="+coordinatesPolygon);
    var plygon = new ol.geom.LineString(coordinatesPolygon);
    //多边形要素类
    var feature = new ol.Feature({
      geometry: plygon,
    });
    vector_line.setZIndex(0);
    source.addFeature(feature);
    map.addLayer(vector_line);
  };

  this.smapline = function (data, className) {
    //画单线  在多个features
    let coordinatesPolygon1 = new Array(data.length);
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        coordinatesPolygon1[i] = [data[i][0], data[i][1]];
      }
    }
    let features = new Array(coordinatesPolygon1.length);
    for (let i = 0; i < coordinatesPolygon1.length; ++i) {
      let coordinate = [coordinatesPolygon1[i][0], coordinatesPolygon1[i][1]];
      features[i] = new ol.Feature(new ol.geom.LineString(coordinate));
      // features[i].set("instanceName","LM1"+i);
    }
    //瓦片图层
    let tileLayer = new ol.layer.Tile({
      source: new ol.source.OSM(),
    });
    let source = new ol.source.Vector();
    //矢量图层
    let vector_line = new ol.layer.Vector({
      className: className,
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: "rgba(255, 255, 255, 0.1)",
        }),
        stroke: new ol.style.Stroke({
          color: "red",
          width: 1,
        }),
        image: new ol.style.Circle({
          radius: 2,
          fill: new ol.style.Fill({
            color: "#ff3344",
          }),
        }),
      }),
    });
    // feature;
    vector_line.setZIndex(0);
    source.addFeatures(features);
    map.addLayer(vector_line);
    /*for (let i = 0; i < features.length; i++) {
            console.log(features[i].get("instanceName"));
            console.log(features[i].getKeys())
            console.log("***********")
        }*/
  };
}

//将一维坐标转换成二维坐标     allArray：二维坐标线上点的集合  currentPos：当前机器人的位置
mapLayer.trigonometric = function (allPoint, currentPos) {
  // currentPos 当前机器人位置  allArray 所有点的位置
  // console.log(currentPos)
  let allArray = mapLayer.unique(allPoint);
  let linepoint = new Array(2); //转换后的点坐标
  let linedis = new Array(allArray.length); //线段分段后的长度
  linedis[0] = 0;
  let allLen = 0;
  for (let i = 0; i < allArray.length - 1; ++i) {
    linedis[i + 1] = parseFloat(
      Math.sqrt(
        (allArray[i + 1][0] - allArray[i][0]) *
          (allArray[i + 1][0] - allArray[i][0]) +
          (allArray[i + 1][1] - allArray[i][1]) *
            (allArray[i + 1][1] - allArray[i][1])
      ).toFixed("3")
    );
  }
  if (currentPos < linedis[0]) {
    let X = allArray[1][0] - allArray[0][0];
    let Y = allArray[1][1] - allArray[0][1];
    let midepoint = new Array(2);
    let onlineLen = currentPos - linedis[0];
    midepoint[0] = (onlineLen / linedis[1]) * X;
    midepoint[1] = (onlineLen / linedis[1]) * Y;
    linepoint[0] = allArray[0][0] + midepoint[0];
    linepoint[1] = allArray[0][1] + midepoint[1];
  }
  for (let i = 0; i < linedis.length - 1; ++i) {
    let star = 0;
    let end = 0;
    for (let j = 0; j <= i; j++) {
      star += linedis[j];
    }
    for (let j = 1; j <= i + 1; j++) {
      end += linedis[j];
    }
    if (currentPos >= star && currentPos <= end) {
      let X = allArray[i + 1][0] - allArray[i][0];
      let Y = allArray[i + 1][1] - allArray[i][1];
      let midepoint = new Array(2);
      let onlineLen = currentPos - star;
      midepoint[0] = (onlineLen / linedis[i + 1]) * X;
      midepoint[1] = (onlineLen / linedis[i + 1]) * Y;
      linepoint[0] = midepoint[0] + allArray[i][0];
      linepoint[1] = midepoint[1] + allArray[i][1];
    }
    allLen = end;
  }
  if (currentPos > allLen) {
    let X = allArray[allArray.length - 1][0] - allArray[allArray.length - 2][0];
    let Y = allArray[allArray.length - 1][1] - allArray[allArray.length - 2][1];
    let midepoint = new Array(2);
    let onlineLen = currentPos - allLen;
    midepoint[0] = (onlineLen / linedis[linedis.length - 1]) * X;
    midepoint[1] = (onlineLen / linedis[linedis.length - 1]) * Y;
    linepoint[0] = midepoint[0] + allArray[allArray.length - 1][0];
    linepoint[1] = midepoint[1] + allArray[allArray.length - 1][1];
  }
  return linepoint;
};
//二维数组去重
mapLayer.unique = function (arr) {
  let hash = {};
  let result = [];
  for (var i = 0, len = arr.length; i < len; i++) {
    if (!hash[arr[i]]) {
      result.push(arr[i]);
      hash[arr[i]] = true;
    }
  }
  return result;
};

mapLayer.getAllLen = function (allArray) {
  alert("1");
  let linedis = new Array(allArray.length); //线段分段后的长度
  linedis[0] = 0;
  for (let i = 0; i < allArray.length - 1; ++i) {
    linedis[i + 1] = parseFloat(
      Math.sqrt(
        (allArray[i + 1][0] - allArray[i][0]) *
          (allArray[i + 1][0] - allArray[i][0]) +
          (allArray[i + 1][1] - allArray[i][1]) *
            (allArray[i + 1][1] - allArray[i][1])
      ).toFixed("3")
    );
  }
  let end = 0;
  for (let i = 0; i < linedis.length; ++i) {
    end += linedis[i];
  }
  return end;
};
mapLayer.getXmax = function (allArray) {
  let arrx = new Array(allArray.length);
  for (let i = 0; i < allArray.length; ++i) {
    arrx[i] = allArray[i][0];
  }
  return Math.max.apply(Math, arrx);
};
mapLayer.getXmin = function (allArray) {
  let arrx = new Array(allArray.length);
  for (let i = 0; i < allArray.length; ++i) {
    arrx[i] = allArray[i][0];
  }
  return Math.min.apply(Math, arrx);
};
mapLayer.getYmax = function (allArray) {
  let arrY = new Array(allArray.length);
  for (let i = 0; i < allArray.length; ++i) {
    arrY[i] = allArray[i][1];
  }
  return Math.max.apply(Math, arrY);
};
mapLayer.getYmin = function (allArray) {
  let arrY = new Array(allArray.length);
  for (let i = 0; i < allArray.length; ++i) {
    arrY[i] = allArray[i][1];
  }
  return Math.min.apply(Math, arrY);
};
mapLayer.initSmapNormalPoint = false;
export default mapLayer;
